﻿using System;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.SessionState;
using Microsoft.Practices.Unity;

namespace Framework
{
	public class ControllerFactory : IControllerFactory
	{
		private readonly IUnityContainer container;
		private readonly IControllerFactory innerFactory;

		public ControllerFactory(IUnityContainer container)
			: this(container, new DefaultControllerFactory())
		{
		}

		private ControllerFactory(IUnityContainer container, IControllerFactory innerFactory)
		{
			this.container = container;
			this.innerFactory = innerFactory;
		}

		public IController CreateController(RequestContext requestContext, string controllerName)
		{

			if (container.IsRegistered<IController>(controllerName.ToLowerInvariant()))
			{
				return container.Resolve<IController>(controllerName.ToLowerInvariant());
			}

			return innerFactory.CreateController(requestContext, controllerName);

		}

		public SessionStateBehavior GetControllerSessionBehavior(RequestContext requestContext, string controllerName)
		{
			return SessionStateBehavior.Default;
		}

		public void ReleaseController(IController controller)
		{
			container.Teardown(controller);
		}
	}
}